package com.yoke.controller.copy;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yoke.common.JsonMessage;
import com.yoke.common.base.DiggingBaseControl;
import com.yoke.common.base.NginxBaseControl;
import com.yoke.common.tools.UrlPath;
import com.yoke.system.log.LogType;
import com.yoke.system.log.SystemLog;
import com.yoke.util.EncryptUtil;
import com.yoke.util.FileUtil;
import com.yoke.util.StringUtil;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

/**
 * Created by jiangzeyin on 2017/7/3.
 */
@Controller
@RequestMapping("copy")
public class CopyIndexControl extends NginxBaseControl {

    @RequestMapping(value = "index.html", produces = MediaType.TEXT_HTML_VALUE)
    public String index(String name) throws IOException {
        request.setAttribute("data", getInfo(UrlPath.Type.None, name, getConfPath()));
        return "copy/index";
    }

    public static JSONObject getInfo(UrlPath.Type type, String name, String path) throws IOException {
        JSONArray jsonArray = UrlPath.start(path, type);
        if (jsonArray == null)
            return null;
        HashMap<String, JSONArray> jsonObjectHashMap = new HashMap<>();
        for (int i = jsonArray.size() - 1; i >= 0; i--) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String userName = jsonObject.getString("userName");
            if (!StringUtil.IsEmpty(name) && !"全部".equals(name))
                if (!userName.equals(name))
                    continue;

            String url = jsonObject.getString("urls");
            if (StringUtil.IsEmpty(url)) {
                url = jsonObject.getString("url");
                int s = url.indexOf("://");
                String tempStr = url.substring(s + 1);
                url = tempStr.substring(0, tempStr.indexOf("/"));
            }
            JSONArray jsonArray1 = jsonObjectHashMap.computeIfAbsent(url, k -> new JSONArray());
            jsonArray1.add(jsonObject);
        }
        return (JSONObject) JSONObject.toJSON(jsonObjectHashMap);
    }


    @RequestMapping(value = "getType.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String save_weixin() {
        File file = new File(getConfPath());
        File[] files = file.listFiles((dir, name) -> new File(dir, name).isDirectory());
        if (files == null)
            return JsonMessage.getString(100, "没有数据");
        JSONArray jsonArray = new JSONArray();
        for (File item : files) {
            jsonArray.add(item.getName());
        }
        return JsonMessage.getString(200, "", jsonArray);
    }

    /**
     * @param tag
     * @return
     */
    @RequestMapping(value = "edit_{tag}.html", produces = MediaType.TEXT_HTML_VALUE)
    public String edit(@PathVariable String tag) {
        String path;
        try {
            path = EncryptUtil.decrypt(tag);
            File file = new File(path);
            if (!file.exists()) {
                request.setAttribute("tip", "编辑失败,文件不存在，请联系管理员");
                return "copy/edit";
            }
            //String context = EncodeFileUtil.readToString(file);
            //if (StringUtil.IsEmpty(context)) {
            // request.setAttribute("tip", "编辑失败,文件内容为null，请联系管理员");
            // return "copy/edit";
            //}
            request.setAttribute("tag_", tag);
            //request.setAttribute("context", context);
        } catch (Exception e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("编辑失败", e);
            request.setAttribute("tip", "编辑失败,参数错误，请联系管理员:" + e.getLocalizedMessage());
            return "copy/edit";
        }
        return "copy/edit";
    }

    @RequestMapping(value = "getContext.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String save_weixin(String tag) {
        String path;
        try {
            path = EncryptUtil.decrypt(tag);
            File file = new File(path);
            if (!file.exists()) {
                return JsonMessage.getString(400, "获取失败,tag 不正确");
            }
            String context = FileUtil.readToString(file);
            return JsonMessage.getString(200, "", context);
        } catch (Exception e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("获取失败", e);
            return JsonMessage.getString(500, "获取失败," + e.getMessage());
        }
    }

    @RequestMapping(value = "save_context.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String save_weixin(String context, String tag) {
        String path;
        try {
            path = EncryptUtil.decrypt(tag);
            File file = new File(path);
            if (!file.exists()) {
                return JsonMessage.getString(100, "保存失败,文件不存在，请联系管理员");
            }
            if (StringUtil.IsEmpty(context))
                return JsonMessage.getString(150, "请输入内容");
            DiggingBaseControl.backIndexHtml(file.getParentFile());
            FileUtil.writeFile(path, context);
            return JsonMessage.getString(200, "保存成功");
        } catch (Exception e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("保存失败", e);
            return JsonMessage.getString(100, "保存失败,请选择正确的文件");
        }
    }
}
